const UserInfo = require("../model/user");
const { Op } = require("sequelize");
const jwt = require("../tools/jwt");
const { jwtSecret } = require("../tools/config");

module.exports = class UserManager {
  /**
   * 增加一个user
   * @param {*} userObj
   * @returns
   */
  static async addAdmin(userObj) {
    const result = await UserInfo.create(userObj);
    return result.toJSON();
  }

  /**
   * 删除一个user
   * @param {*} userId
   */
  static async deleteAdmin(userId) {
    const result = await UserInfo.destroy({
      where: {
        id: userId,
      },
    });
  }
  /**
   * 批量删除user
   * @param {*} id
   */
  static async bulkDelete(params) {
    let promises;
    const _this = this;
    const delRes = [];
    if (params.length > 0) {
      promises = params.map(async (item) => {
        const res = await _this.deleteAdmin(item);
        delRes.push(res);
      });
    }
    await Promise.all(promises);
  }

  /**
   * 更新user
   * @param {*} userId
   * @param {*} userObj
   */
  static async updateAdmin(userId, userObj) {
    await UserInfo.update(userObj, {
      where: {
        id: userId,
      },
    });
    const result = await UserInfo.findOne({
      where: {
        id: userId,
      },
    });
    return result;
  }

  /**
   * 查询所有的user
   * @returns
   */
  static async getAllAdmin() {
    const result = await UserInfo.findAll();
    return JSON.parse(JSON.stringify(result));
  }

  /**
   *分页查询 user
   * @returns
   */
  static async find(page = 1, limit = 10, name, level, searchLevel) {
    const where = {};
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`,
      };
    }
    if (level) {
      if (level == 1) {
        if (searchLevel) {
          where.level = searchLevel;
        } else {
          where.level = {
            [Op.in]: [2, 0],
          };
        }
      } else if (level == 2) {
        where.level = 0;
      }
    }
    console.log("searchLevel", searchLevel);
    console.log("level", level);
    console.log("where", where);
    const result = await UserInfo.findAndCountAll({
      where,
      offset: (page - 1) * limit,
      limit: +limit,
      order: [["createdAt", "DESC"]],
    });
    return JSON.parse(JSON.stringify(result));
  }

  /**
   * 根据id查询user
   * @returns
   */
  static async getAdminById(id) {
    const result = await UserInfo.findOne({
      where: {
        id,
      },
    });
    if (result === null) {
      console.log("getAdminById user Not found!");
    } else {
      return JSON.parse(JSON.stringify(result));
    }
  }
  /**
   * 登录
   * @returns
   */
  static async login(loginId, loginPwd) {
    console.log("loginId", loginId);
    console.log("loginPwd", loginPwd);
    const resultByUser = await UserInfo.findOne({
      where: {
        username: loginId,
      },
    });

    if (resultByUser === null) {
      console.log("login user Not found!");
      throw new Error("用户或密码错误！");
    } else if (resultByUser.username != loginId) {
      console.log("resultByUser", resultByUser.user);
      throw new Error("用户或密码错误！");
    } else {
      const result = await UserInfo.findOne({
        where: {
          username: loginId,
          passwd: loginPwd,
        },
      });
      if (result === null) {
        throw new Error("用户或密码错误！");
      } else {
        const user = JSON.parse(JSON.stringify(result));
        const token = await jwt.sign({ userId: user.id }, jwtSecret);
        // 更新用户的当前有效token
        await UserInfo.update(
          { currentToken: token },
          { where: { id: user.id } }
        );
        return { ...user, currentToken: token, token };
      }
    }
  }
  /**
   * 验证token
   * @returns
   */
  static async verifyToken(token) {
    try {
      const decoded = await jwt.verify(token, jwtSecret);
      const user = await UserInfo.findOne({
        where: {
          id: decoded.userId,
          currentToken: token,
        },
      });
      if (user === null) {
        throw new Error("无效的token！");
      } else {
        return user;
      }
    } catch (err) {
      throw new Error("token验证失败！");
    }
  }
};
